import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_aliplayer/flutter_aliplayer.dart';
import 'package:get/get.dart';
import 'package:projectfluttershengyihuatong/courseDetail/courseviewmodel.dart';
import 'package:projectfluttershengyihuatong/courseDetail/playermanger.dart';
import 'package:projectfluttershengyihuatong/route.dart';
import 'package:projectfluttershengyihuatong/tab2/customview.dart';
import 'package:projectfluttershengyihuatong/tool/player/model/playauth_model.dart';
import 'package:projectfluttershengyihuatong/tool/public_color.dart';

import '../tool/player/config.dart';
import '../tool/tool.dart';
import 'CourseDetailModel.dart';
import 'package:get/get.dart';

class CourseDetail extends StatefulWidget {
  const CourseDetail({super.key});

  @override
  State<CourseDetail> createState() => _CourseDetailState();
}

class _CourseDetailState extends State<CourseDetail> {
  @override
  void initState() {
    final args = Get.arguments as Map<String, String>;
    courseId = args["courseId"];
    kid = args["kid"];
    if (kid != null && kid!.isNotEmpty) {
      manager.kid = int.parse(kid!);
    }
    future = viewModel.request({"course_id": courseId ?? "", "kid": kid ?? ""});
    // TODO: implement initState

    super.initState();
  }

  late Future<CourseDetailModel?> future;
  final viewModel = CourseDetailViewModel();
  late final String? courseId;
  late final String? kid;
  late PlayerManager manager = PlayerManager(ModeType.AUTH);

  @override
  Widget build(BuildContext context) {
    var x = 0.0;
    var y = 0.0;
    Orientation orientation = MediaQuery.of(context).orientation;
    var width = MediaQuery.of(context).size.width;

    var height;
    if (orientation == Orientation.portrait) {
      height = width * 9.0 / 16.0;
    } else {
      height = MediaQuery.of(context).size.height;
    }

    AliPlayerView aliPlayerView = AliPlayerView(
      onCreated: onViewPlayerCreated,
      x: x,
      y: y,
      width: width,
      height: height,
      aliPlayerViewType: AliPlayerViewTypeForAndroid.surfaceview,
    );
    return Scaffold(
      body: FutureBuilder(
        future: future,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            final teachers = viewModel.dataModel?.teacherInfo ?? [];
            final courseDetailImage = viewModel.dataModel?.courseDetail.imgUrl ?? "";
            return OrientationBuilder(builder: (context, orientation) {
              return SafeArea(
                  child: Container(
                color: colorfa,
                child: Column(
                  children: [
                    Stack(
                      children: [
                        Container(
                            color: Colors.black,
                            width: width,
                            height: height,
                            child: aliPlayerView),
                      ],
                    ),
                    Expanded(
                      child: CustomScrollView(
                        slivers: [
                          CourseDetailHeader(viewModel: viewModel),
                          CourseDetailTeacher(teachers: teachers),
                          SliverToBoxAdapter(
                            child: Container(
                              child:  DefaultTabController(
                                length: 3,
                                child: SingleChildScrollView(
                                  child: Column(
                                    children: [
                                      TabBar(
                                          indicatorColor: primaryColor,
                                          labelColor: primaryColor,
                                          indicatorPadding: EdgeInsets.only(bottom: 0),
                                          tabs:  [
                                            const Padding(
                                              padding: EdgeInsets.only(top: 0, bottom: 12),
                                              child: Text("详情"),
                                            ),
                                            GestureDetector(
                                              onTap: (){
                                  
                                              },
                                              child: const Padding(
                                                padding: EdgeInsets.only(bottom: 12),
                                                child: Stack(
                                                  children: [Text("目录")],
                                                ),
                                              ),
                                            ),
                                            GestureDetector(
                                              onTap: (){
                                  
                                              },
                                              child: const Padding(
                                                padding: EdgeInsets.only(bottom: 12),
                                                child: Text("去做题"),
                                              ),
                                            )
                                          ]),
                                      Container(
                                        child: Image.network(courseDetailImage,width: double.infinity,fit: BoxFit.fitHeight,errorBuilder: (context,a, b){
                                          return Image.asset(assetImage("icon-imageError"));
                                        },),
                                      ),

                                  
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ));
            });
          }
          return const Center(child: CircularProgressIndicator());
        },
      ),
    );
  }

  SliverPadding buildChapterLesson() {
    return SliverPadding(
                          padding: const EdgeInsets.only(
                              left: 8, right: 8, top: 0, bottom: 10),
                          sliver: SliverToBoxAdapter(
                            child: SingleChildScrollView(
                              child: Container(
                                child: CustomExpansionPanelList(
                                  expandedHeaderPadding: EdgeInsets.zero,
                                  elevation: 0,
                                  dividerColor: colorfa,
                                  materialGapSize: 10,
                                  children: buildPanelList(),
                                ),
                              ),
                            ),
                          ),
                        );
  }

  buildPanelList() {
    final chapters = viewModel.dataModel?.chapterAndLesson ?? [];

    final panels = chapters.map((chapter) {
      final chapterLiveVideosIsNoyEmpty =
          chapter.liveVideoData?.isNotEmpty ?? false;
      return ExpansionPanel(
          isExpanded: chapter.isSelected,
          headerBuilder: (context, isexpand) {
            return buildHeader(chapter);
          },
          body: buildPanelBody(
              chapterIsEmpty: chapterLiveVideosIsNoyEmpty, chapter: chapter));
    }).toList();
    return panels;
  }

  Container buildHeader(CourseChapterLesson chapter) {
    return Container(
      height: 50,
      child: Row(
        children: [
          IconButton(
            isSelected: chapter.isSelected,
            onPressed: () {
              chapter.isSelected = !(chapter.isSelected);
              // widget.callback(widget.model?.isSelected ?? false);
              setState(() {});
            },
            icon: Image.asset(
              assetImage("icon-shouqi"),
              width: 15,
              height: 15,
            ),
            selectedIcon: Image.asset(
              assetImage("icon-zhankai"),
              width: 15,
              height: 15,
            ),
          ),
          Expanded(
              child: Text(
            chapter.name ?? "",
            style: TextStyle(color: color33, fontWeight: FontWeight.bold),
          ))
        ],
      ),
    );
  }

  buildPanelBody(
      {required bool chapterIsEmpty, required CourseChapterLesson chapter}) {
    if (chapterIsEmpty) {
      return buildListView(chapter);
    } else {
      return SingleChildScrollView(
        child: Container(
          child: CustomExpansionPanelList(
            children: chapter.children?.map((children) {
                  return ExpansionPanel(
                      headerBuilder: (context, _) {
                        return buildHeader(children);
                      },
                      body: buildListView(children));
                }).toList() ??
                [],
          ),
        ),
      );
    }
  }

  ListView buildListView(CourseChapterLesson chapter) {
    return ListView.separated(
      itemBuilder: (context, index) {
        final videoModel = chapter.liveVideoData?[index];
        if (videoModel == null) {
          return Container();
        }
        final liveOrVideo = videoModel!.isLiveBroadcast ?? 0;
        final isPlaying = videoModel.isPlaying;
        final imageStr = liveOrVideo == 1
            ? assetImage(isPlaying ? "liveing.gif" : "icon-chapterzhibohui")
            : assetImage(
                isPlaying ? "icon-chapterplay" : "icon-chapterunPlaye");
        return GestureDetector(
          onTap: () async {
            if (videoModel.isPlaying) {
              return;
            }
            Map<String, String> map = {};
            manager.kid = videoModel.kid?.toInt() ?? 0;
            map = await manager.requestAuth();

            manager.aliplayer.setVidAuth(
              vid: map[DataSourceRelated.VID_KEY],
              region: map[DataSourceRelated.REGION_KEY],
              playAuth: map[DataSourceRelated.PLAYAUTH_KEY],
            );
            manager.aliplayer.prepare();
            manager.aliplayer.play();
          },
          child: Stack(
            children: [
              Container(
                padding: const EdgeInsets.all(10),
                color: Colors.white,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                        width: 40,
                        child: Center(
                            child: Image.asset(
                          imageStr,
                          width: 20,
                          fit: BoxFit.fitWidth,
                        ))),
                    Expanded(
                        child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          videoModel.title ?? "",
                          style: TextStyle(
                            color: color66,
                            fontSize: 14,
                          ),
                        ),
                        const SizedBox(
                          height: 3,
                        ),
                        Text(
                          "进度${videoModel.videoSchedule ?? 0}%",
                          style: TextStyle(color: color99, fontSize: 12),
                        ),
                      ],
                    )),
                    if (!videoModel.hasPrivilege)
                      Image.asset(
                        assetImage("icon-chaptersuoding"),
                        width: 18,
                        fit: BoxFit.fitWidth,
                      )
                  ],
                ),
              ),
              if (isPlaying)
                Positioned(
                  right: 10,
                  top: 0,
                  child: Container(
                    padding: const EdgeInsets.only(
                        left: 3, right: 3, top: 2, bottom: 2),
                    decoration: BoxDecoration(
                      color: primaryColor,
                      borderRadius: BorderRadius.circular(2),
                    ),
                    child: const Text(
                      "正在播放",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                      ),
                    ),
                  ),
                ),
            ],
          ),
        );
      },
      separatorBuilder: (context, index) {
        return const Divider(
          height: 1,
          thickness: 1,
          color: Colors.yellow,
        );
      },
      itemCount: chapter.liveVideoData?.length ?? 0,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
    );
  }

  void onViewPlayerCreated(viewId) async {
    manager.aliPlayerViewId = viewId;
    await manager.aliplayer.setPlayerView(viewId);
    final map = await manager.aliplayer.getConfig() as Map<Object?, Object?>;
    map["mReferrer"] = "https://app.syht.xyz";
    manager.aliplayer.setConfig(map);
    await manager.generatePlayConfigGen();
    switch (manager.playMode) {
      case ModeType.URL:
        final map = await manager.requestAuth();
        // manager.aliplayer.setUrl(map[DataSourceRelated.URL_KEY]);
        break;
      case ModeType.STS:
        // FlutterAliplayer.generatePlayerConfig().then((value) {
        //
        // });

        // manager.aliplayer.setVidSts(
        //     vid: _dataSourceMap[DataSourceRelated.VID_KEY],
        //     region: _dataSourceMap[DataSourceRelated.REGION_KEY],
        //     accessKeyId: _dataSourceMap[DataSourceRelated.ACCESSKEYID_KEY],
        //     accessKeySecret:
        //     _dataSourceMap[DataSourceRelated.ACCESSKEYSECRET_KEY],
        //     securityToken:
        //     _dataSourceMap[DataSourceRelated.SECURITYTOKEN_KEY],
        //     definitionList: _dataSourceMap[DataSourceRelated.DEFINITION_LIST]);

        break;
      case ModeType.AUTH:
        final map = await manager.requestAuth();

        final value = jsonEncode(map);
        manager.aliplayer.setVidAuth(
          vid: map[DataSourceRelated.VID_KEY],
          region: map[DataSourceRelated.REGION_KEY],
          playAuth: map[DataSourceRelated.PLAYAUTH_KEY],
        );
        manager.aliplayer.prepare();
        manager.aliplayer.onPrepared = (playerId){
          manager.aliplayer.play();
        };
        manager.aliplayer.onError = (int errorCode, String? errorExtra, String? errorMsg, String playerId){
          print('error = ${errorCode} ${errorExtra ?? ""} ${errorMsg ?? ""} ${playerId}');
        };
        break;
      case ModeType.MPS:
        // manager.aliplayer.setVidMps(_dataSourceMap);
        break;
      default:
    }
  }

  @override
  void dispose() {
    manager.aliplayer.stop();
    manager.aliplayer.destroy();

    // TODO: implement dispose
    super.dispose();
  }
}

class CourseDetailHeader extends StatelessWidget {
  const CourseDetailHeader({
    super.key,
    required this.viewModel,
  });

  final CourseDetailViewModel viewModel;

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.only(
            left: 12, right: 12, top: 10, bottom: 10),
        child: Text(
          viewModel.dataModel?.courseDetail.name ?? "",
          style: TextStyle(
            color: color33,
            fontSize: 18,
            fontWeight: FontWeight.bold
          ),
        ),
      ),
    );
  }
}

class CourseDetailTeacher extends StatelessWidget {
  const CourseDetailTeacher({
    super.key,
    required this.teachers,
  });

  final List<TeacherInfo> teachers;

  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Container(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 50,
              child: Text("教师", style: TextStyle(
                color: color33,
                fontSize: 14,
                fontWeight: FontWeight.bold,
              ),),
            ),
            Container(
              height: 70,
              child: ListView(
                scrollDirection: Axis.horizontal,
                children: List.generate(teachers.length, (index){
                  final teacher = teachers[index];
                  return Container(
                    width: 120,
                    padding: const EdgeInsets.only(left: 10,right: 5),
                    color: colorf1,
                    margin: const EdgeInsets.only(right: 10),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(30),
                            child: Image.network(
                          teacher.img,
                          errorBuilder: (context, a, b){
                            return Image.asset(assetImage("icon-imageError"),width: 30, height: 30,fit: BoxFit.fill,);
                          },

                          width: 30,
                              height: 30,
                          fit: BoxFit.fitWidth,
                        )),
                        const SizedBox(width: 3,),
                        Expanded(
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(teacher.name,),
                              const SizedBox(height: 4,),
                              Text(teacher.company),
                            ],
                          ),
                        ),
                      ],
                    ),
                  );
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
